package ru.spies.work;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;

import ru.spies.dbwork.DBQueries;
import ru.spies.dbwork.DBWork;
import ru.spies.entities.Agent;
import ru.spies.entities.Agentsandtask;
import ru.spies.entities.Country;
import ru.spies.entities.Department;
import ru.spies.entities.Document;
import ru.spies.entities.Importance;
import ru.spies.entities.Task;
import ru.spies.entities.TaskType;
import ru.spies.help.MyLogger;
import ru.spies.profileClasses.UserInfo;
import ru.spies.requests.AddRequestWork;


public class ShowWork extends AbstractWork{
	
	private static ShowWork statThis=null;
	private static final String NOTHING="Отсутствует";
	
	private ShowWork() {
		
	}
	
	public static ShowWork getInstance(){
		if (statThis==null){
			statThis = new ShowWork();
		}
		return statThis;
	}

	@Override
	protected void doWorkWithAgent(HttpServletRequest request) {
		StringBuffer dataTableFileContent = new StringBuffer();	
		Department lastDepartment=AddRequestWork.getInstance().getLastDepartment();
		Collection<Department> departments;
		Collection<Department> mineDepartments = new Vector<Department>();
		if (lastDepartment==null){
			departments=(Collection<Department>) DBWork.getInstance().getTableObjects(DBQueries.QUERY_DEPARTMENT_FIND);
			if (!UserInfo.getInstance().getPrivileges().canDoNormalShow()){
				for (Department department : departments) {
					if (department.getCountry().getId().intValue()==UserInfo.getInstance().getMe().getAgent().getDepartment().getCountry().getId().intValue()){
						mineDepartments.add(department);
					}
				}
			} else {
				mineDepartments=departments;
			}
		} else {
			mineDepartments.add(lastDepartment);
		}
		for (Department department : mineDepartments){
			for (Agent i:department.getAgents()){
				dataTableFileContent.append("{ \"recruiter\" : \"");
				Agent recruiter = i.getRecruiter();
				String recruiterName=NOTHING;
				if (recruiter!=null){
					recruiterName=recruiter.getName();
				}
				dataTableFileContent.append(recruiterName);
				dataTableFileContent.append("\", \"department\" : \"");
				dataTableFileContent.append(department.getName());
				dataTableFileContent.append("\", \"name\" : \"");
				dataTableFileContent.append(i.getName());
				dataTableFileContent.append("\", \"countRecruits\" : \"");
				dataTableFileContent.append(i.getCountRecruits());
				dataTableFileContent.append("\", \"status\" : \"");
				dataTableFileContent.append(convertAgentStatus(i.getStatus()));
				dataTableFileContent.append("\"},");
			}
		}
		if (dataTableFileContent.length()>16){
		dataTableFileContent.replace(dataTableFileContent.lastIndexOf(","), dataTableFileContent.length(), "");
		} else {
			dataTableFileContent.append("{ \"recruiter\" : \""+NOTHING+" \", \"department\" : \""+NOTHING+" \", \"name\" : \""+NOTHING+" \", \"countRecruits\" : \""+NOTHING+" \", \"status\" : \""+NOTHING+" \"}");
		}
		dataTableFileContent=getWrapper(dataTableFileContent);
		createFileForDataTable(dataTableFileContent.toString());
	}

	@Override
	protected void doWorkWithAgentAndTask(HttpServletRequest request) {
		StringBuffer dataTableFileContent = new StringBuffer();	
		Collection<Agentsandtask> agentsAndTasks =  (Collection<Agentsandtask>) DBWork.getInstance().getTableObjects(DBQueries.QUERY_AGENT_AND_TASK_FIND);
		Collection<Agentsandtask> mineAgentsAndTasks = new Vector<Agentsandtask>();
		if (!UserInfo.getInstance().getPrivileges().canDoNormalShow()){
			for (Agentsandtask i : agentsAndTasks) {
				if (i.getTask().getCountry().getId().intValue()==UserInfo.getInstance().getMe().getAgent().getDepartment().getCountry().getId().intValue()){
					mineAgentsAndTasks.add(i);
				}
			}
		} else {
			mineAgentsAndTasks=agentsAndTasks;
		}
		for (Agentsandtask i:mineAgentsAndTasks){
			dataTableFileContent.append("{ \"agent\" : \"");
			Agent agent = i.getAgent();
			String agentName=NOTHING;
			if (agent!=null){
				agentName=agent.getName();
			}
			dataTableFileContent.append(agentName);
			Task task = i.getTask();
			String taskName=NOTHING;
			if (task!=null){
				taskName=task.getName();
			}
			dataTableFileContent.append("\", \"task\" : \"");
			dataTableFileContent.append(taskName);
			dataTableFileContent.append("\"},");
		}
		if (dataTableFileContent.length()>16){
			dataTableFileContent.replace(dataTableFileContent.lastIndexOf(","), dataTableFileContent.length(), "");
		} else {
			dataTableFileContent.append("{ \"agent\" : \""+NOTHING+" \", \"task\" : \""+NOTHING+" \"}");
		}
		dataTableFileContent=getWrapper(dataTableFileContent);
		createFileForDataTable(dataTableFileContent.toString());	
	}

	@Override
	protected void doWorkWithCountry(HttpServletRequest request) {
		StringBuffer dataTableFileContent = new StringBuffer();	
		Collection<Country> countries =  (Collection<Country>) DBWork.getInstance().getTableObjects(DBQueries.QUERY_COUNTRY_FIND);
		Collection<Country> mineCountries = new Vector<Country>();
		if (!UserInfo.getInstance().getPrivileges().canDoNormalShow()){
			for (Country country : countries) {
				if (UserInfo.getInstance().getMe().getAgent().getDepartment().getCountry().getId().intValue()==country.getId().intValue()){
					mineCountries.add(country);
				}
			}
		} else {
			mineCountries=countries;
		}
		for (Country i:mineCountries){
			dataTableFileContent.append("{ \"name\" : \"");
			dataTableFileContent.append(i.getName());
			dataTableFileContent.append("\", \"relation\" : \"");
			dataTableFileContent.append(getRelationFromCountry(i.getRelation()));
			dataTableFileContent.append("\"},");
		}
		if (dataTableFileContent.length()>16){
			dataTableFileContent.replace(dataTableFileContent.lastIndexOf(","), dataTableFileContent.length(), "");
		} else {
			dataTableFileContent.append("{ \"name\" : \""+NOTHING+" \", \"relation\" : \""+NOTHING+" \"}");
		}
		dataTableFileContent=getWrapper(dataTableFileContent);
		createFileForDataTable(dataTableFileContent.toString());
	}

	@Override
	protected void doWorkWithDepartment(HttpServletRequest request) {
		StringBuffer dataTableFileContent = new StringBuffer();	
		Country lastCountry=AddRequestWork.getInstance().getLastCountry();
		Collection<Country> countries;
		Collection<Country> mineCountries = new Vector<Country>();
		if (lastCountry==null){
			countries=(Collection<Country>) DBWork.getInstance().getTableObjects(DBQueries.QUERY_COUNTRY_FIND);
			if (!UserInfo.getInstance().getPrivileges().canDoNormalShow()){
				for (Country country : countries) {
					if (UserInfo.getInstance().getMe().getAgent().getDepartment().getCountry().getId().intValue()==country.getId().intValue()){
						mineCountries.add(country);
					}
				}
			} else {
				mineCountries=countries;
			}
		} else {
			mineCountries.add(lastCountry);
		}
		SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yy");
		for (Country country : mineCountries){
			for (Department i:country.getDepartments()){
				dataTableFileContent.append("{ \"country\" : \"");
				dataTableFileContent.append(country.getName());
				dataTableFileContent.append("\", \"resident\" : \"");
				Agent agent=i.getResident();
				String agentName=NOTHING;
				if (agent!=null){
					agentName=agent.getName();
				}
				dataTableFileContent.append(agentName);
				dataTableFileContent.append("\", \"name\" : \"");
				dataTableFileContent.append(i.getName());
				dataTableFileContent.append("\", \"description\" : \"");
				dataTableFileContent.append(i.getDescription());
				dataTableFileContent.append("\", \"creationDate\" : \"");
				dataTableFileContent.append(sdf.format(i.getCreationDate()));
				dataTableFileContent.append("\"},");
			}
		}
		if (dataTableFileContent.length()>16){
			dataTableFileContent.replace(dataTableFileContent.lastIndexOf(","), dataTableFileContent.length(), "");
		} else {
			dataTableFileContent.append("{ \"country\" : \""+NOTHING+" \", \"resident\" : \""+NOTHING+" \", \"name\" : \""+NOTHING+" \", \"description\" : \""+NOTHING+" \", \"creationDate\" : \""+NOTHING+" \"}");
		}
		dataTableFileContent=getWrapper(dataTableFileContent);
		createFileForDataTable(dataTableFileContent.toString());
	}

	@Override
	protected void doWorkWithDocument(HttpServletRequest request) {
		StringBuffer dataTableFileContent = new StringBuffer();	
		Collection<Document> docs =  (Collection<Document>) DBWork.getInstance().getTableObjects(DBQueries.QUERY_DOCUMENT_FIND);
		Collection<Document> mineDocs = new Vector<Document>();
		if (!UserInfo.getInstance().getPrivileges().canDoNormalShow()){
			for (Document document : docs) {
				if (isThisDocumentMineOrFromMineDepartment(document)){
					mineDocs.add(document);
				}
			}
		} else {
			mineDocs=docs;
		}
		for (Document i:mineDocs){
			dataTableFileContent.append("{ \"task\" : \"");
			Task task = i.getTask();
			String taskName=NOTHING;
			if (task!=null){
				taskName=task.getName();
			}
			dataTableFileContent.append(taskName);
			dataTableFileContent.append("\", \"importance\" : \"");
			dataTableFileContent.append(i.getImportance().getType());
			dataTableFileContent.append("\", \"textLink\" : \"");
			dataTableFileContent.append(i.getTextLink());
			dataTableFileContent.append("\"},");			
		}
		if (dataTableFileContent.length()>16){
			dataTableFileContent.replace(dataTableFileContent.lastIndexOf(","), dataTableFileContent.length(), "");
		} else {
			dataTableFileContent.append("{ \"task\" : \""+NOTHING+" \", \"importance\" : \""+NOTHING+" \", \"textLink\" : \""+NOTHING+" \"}");
		}
		dataTableFileContent=getWrapper(dataTableFileContent);
		createFileForDataTable(dataTableFileContent.toString());
		
	}

	@Override
	protected void doWorkWithImportance(HttpServletRequest request) {
		StringBuffer dataTableFileContent = new StringBuffer();	
		Collection<Importance> importances =  (Collection<Importance>) DBWork.getInstance().getTableObjects(DBQueries.QUERY_IMPORTANCE_FIND);
		for (Importance i:importances){
			dataTableFileContent.append("{   \"type\"  : \"");
			dataTableFileContent.append(i.getType());
			dataTableFileContent.append("\"  },");
		}
		if (dataTableFileContent.length()!=0){
			dataTableFileContent.replace(dataTableFileContent.lastIndexOf(","), dataTableFileContent.length(), "");
		} else {
			dataTableFileContent.append("{ \"type\" : \""+NOTHING+" \" }");
		}
		dataTableFileContent=getWrapper(dataTableFileContent);
		createFileForDataTable(dataTableFileContent.toString());	
	}

	@Override
	protected void doWorkWithTask(HttpServletRequest request) {
		StringBuffer dataTableFileContent = new StringBuffer();	
		Collection<Country> countries;
		Collection<Country> mineCountries = new Vector<Country>();
		Country lastCountry=AddRequestWork.getInstance().getLastCountry();
		if (lastCountry==null){
			countries =  (Collection<Country>) DBWork.getInstance().getTableObjects(DBQueries.QUERY_COUNTRY_FIND);
			if (!UserInfo.getInstance().getPrivileges().canDoNormalShow()){
				for (Country country : countries) {
					if (UserInfo.getInstance().getMe().getAgent().getDepartment().getCountry().getId().intValue()==country.getId().intValue()){
						mineCountries.add(country);
					}
				}
			} else {
				mineCountries=countries;
			}
		} else {
			mineCountries.add(lastCountry);
		}
		for (Country country:mineCountries){
			for(Task i:country.getTasks()){
				Importance importance = i.getImportance();
				String importanceType = NOTHING;
				if (importance!=null){
					importanceType=importance.getType();
				}
				dataTableFileContent.append("{ \"importance\" : \"");
				dataTableFileContent.append(importanceType);
				dataTableFileContent.append("\", \"country\" : \"");
				dataTableFileContent.append(i.getCountry().getName());
				TaskType taskType = i.getTaskType();
				String taskTypeName = NOTHING;
				if (taskType!=null){
					taskTypeName=taskType.getTypeName();
				}
				dataTableFileContent.append("\", \"type\" : \"");
				dataTableFileContent.append(taskTypeName);
				dataTableFileContent.append("\", \"name\" : \"");
				dataTableFileContent.append(i.getName());
				dataTableFileContent.append("\", \"status\" : \"");
				dataTableFileContent.append(getTaskStatus(i.getStatus()));
				dataTableFileContent.append("\"},");
			}
		}
		if (dataTableFileContent.length()>16){
			dataTableFileContent.replace(dataTableFileContent.lastIndexOf(","), dataTableFileContent.length(), "");
		} else {
			dataTableFileContent.append("{ \"importance\" : \""+NOTHING+" \", \"country\" : \""+NOTHING+" \", \"type\" : \""+NOTHING+" \", \"name\" : \""+NOTHING+" \", \"status\" : \""+NOTHING+" \"}");
		}
		dataTableFileContent=getWrapper(dataTableFileContent);
		createFileForDataTable(dataTableFileContent.toString());
	}

	@Override
	protected void doWorkWithTaskType(HttpServletRequest request) {
		StringBuffer dataTableFileContent = new StringBuffer();	
		Collection<TaskType> tasktypes =  (Collection<TaskType>) DBWork.getInstance().getTableObjects(DBQueries.QUERY_TASK_TYPE_FIND);
		for (TaskType i:tasktypes){
			dataTableFileContent.append("{ \"typeName\" : \"");
			dataTableFileContent.append(i.getTypeName());
			dataTableFileContent.append("\"},");
		}
		if (dataTableFileContent.length()>16){
			dataTableFileContent.replace(dataTableFileContent.lastIndexOf(","), dataTableFileContent.length(), "");
		} else {
			dataTableFileContent.append("{ \"typeName\" : \""+NOTHING+" \"}");
		}
		dataTableFileContent=getWrapper(dataTableFileContent);
		createFileForDataTable(dataTableFileContent.toString());	
	}

	private void createFileForDataTable(String text){
		String fileName = ShowResults.getInstance().getMainPath()+ShowResults.getInstance().getFileName()+".txt";
		File f = new File(fileName);
		if (f.exists()){
			f.delete();
		}
		try {
			f.createNewFile();
		} catch (IOException e) {
			MyLogger.getInstance().getLog().error(MyLogger.EXCEPTION,e);
		}
		Writer out;
		try {
			out = new OutputStreamWriter(new FileOutputStream(f),"UTF-8");
			out.write(text);
			out.close();
		} catch (IOException e) {
			MyLogger.getInstance().getLog().error(MyLogger.EXCEPTION,e);
		}
	}

	private StringBuffer getWrapper(StringBuffer textToWrap){
		StringBuffer wrapper = new StringBuffer();
		wrapper.append("{ \"aaData\": [ ");
		wrapper.append(textToWrap);
		wrapper.append(" ] }");
		return wrapper;
	}
	
	private String getRelationFromCountry(String relation){
		if (relation==null)	return NOTHING;
		if (relation.equals("enemy")) return "Вражеские";
		if (relation.equals("friend")) return "Дружеские";
		if (relation.equals("neutral")) return "Нейтральные";
		return NOTHING;
	}
	
	private String convertAgentStatus(boolean value){
		if (value){
			return "Раскрыт";
		} else {
			return "Не раскрыт";
		}
	}
	
	private String getTaskStatus(String status){
		if (status.equals("a")) return "Активно";
		if (status.equals("c")) return "Успешно завершено";
		return "Провалено!";
	}
	
	protected boolean isThisDocumentMineOrFromMineDepartment(Document doc){
		UserInfo currentInfo=UserInfo.getInstance();
		if (!currentInfo.getPrivileges().canDoNormalShow()){
			if (currentInfo.getMe().getAgent().getId().intValue()==doc.getAgent().getId().intValue()){
				return true;
			}
			if (currentInfo.isRoleResident()){
				if (doc.getAgent().getDepartment().getId().intValue()==currentInfo.getMe().getAgent().getDepartment().getId().intValue()){
					return true;
				}
			}
		}
		return false;
	}
	
}
